package com.example.springboot.oauth2;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;

import javax.sql.DataSource;

@Configuration
public class OAuth2Configuration {

    private final static Logger log = LoggerFactory.getLogger(OAuth2Configuration.class);


    /**配置安全资源服务器*/
    @Configuration
    @EnableResourceServer
    protected static class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

        @Autowired
        private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;

        @Autowired
        private CustomLogoutSuccessHandler customLogoutSuccessHandler;

        @Override
        public void configure(HttpSecurity http) throws Exception {

            http
                    .exceptionHandling()
                    .authenticationEntryPoint(customAuthenticationEntryPoint)
                    .and()
                    .logout()
                    .logoutUrl("/oauth/logout")
                    .logoutSuccessHandler(customLogoutSuccessHandler)
                    .and()
                    .authorizeRequests()
                    //排除了对/hello公开地址拦截
                    .antMatchers("/hello/").permitAll()
                    //限定scope访问
                    .antMatchers("/secure/u").access("#oauth2.hasScope('"+Scopes.write.name()+"')")
                    .antMatchers("/secure/go").access("#oauth2.hasScope('"+Scopes.execute.name()+"')")
                    ///secure下的所有地址都必须授权才可以访问
                    .antMatchers("/secure/**").authenticated();


            log.info("ResourceServerConfiguration HttpSecurity configure");
        }

    }

    /**开启OAuth2验证服务器*/
    @Configuration
    @EnableAuthorizationServer
    protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {

        @Value("${authentication.oauth.clientid:wuning_home_pc}")//默认值设为wuning_home_pc
        private String clientID;

        @Value("${authentication.oauth.secret:secret_home_pc}")//默认值设为
        private String secret;

        @Value("${authentication.oauth.tokenValidityInSeconds:1800}")//默认值设为1800
        private int tokenValidityInSeconds;

        @Autowired
        private DataSource dataSource;

        @Autowired
        private PasswordEncoder passwordEncoder;

        @Bean
        public TokenStore tokenStore() {
            return new JdbcTokenStore(dataSource);
        }

        @Autowired
        @Qualifier("authenticationManagerBean")
        private AuthenticationManager authenticationManager;

        @Override
        public void configure(AuthorizationServerEndpointsConfigurer endpoints)
                throws Exception {
            endpoints
                    .tokenStore(tokenStore())
                    .authenticationManager(authenticationManager);
            log.info("AuthorizationServerConfiguration AuthorizationServerEndpointsConfigurer");
        }

        @Override
        public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
            clients
                    .inMemory()
                    //（必须的）客户端ID
                    .withClient(clientID)
                    //（对于信任的客户端需要）客户端秘钥
                    .secret(passwordEncoder.encode(secret))
                    //客户端被限定的范围。如果scope为定义或者为空（默认为空）则客户端不受scope限制
                    .scopes(Scopes.read.name(), Scopes.write.name(),Scopes.execute.name())
                    //客户端被限定的权限范围
                    .authorities(Authorities.ROLE_ADMIN.name(), Authorities.ROLE_USER.name(),Authorities.ROLE_ANONYMOUS.name())
                    //客户端使用到的授权类型
                    .authorizedGrantTypes(/*"password", */"authorization_code", "refresh_token")
                    //access_token 的有效时长
                    .accessTokenValiditySeconds(tokenValidityInSeconds);

            log.info("AuthorizationServerConfiguration ClientDetailsServiceConfigurer");
        }

    }


    /*1、获取授权码
    http://localhost:8080/oauth/authorize?client_id=test_clientid&response_type=code&redirect_uri=http://www.jianshu.com
    */
    /*2、换取访问令牌
    http://localhost:8080/oauth/token?grant_type=authorization_code&code=VgYk9v&client_id=test_clientid&redirect_uri=http://www.jianshu.com
    */
}
